package app

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/thedevsaddam/gojsonq/v2"
	"io/ioutil"
	"net/http"
	"testPaper/response"
)

const (
	code2sessionURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
	appID           = "wxdb90bcb18b945213"               //微信appID
	appSecret       = "87d8b9a20b4980a0cb73ed97d38a6b81" //微信AppSecret
)

// QueryOpenId 获取微信openid
func QueryOpenId(c *gin.Context) {
	//获取code
	code := c.PostForm("code")

	//调用auth.code2Session接口获取openid
	url := fmt.Sprintf(code2sessionURL, appID, appSecret, code)
	resp, err := http.Get(url)
	if err != nil {
		response.Reponse(c, http.StatusUnprocessableEntity, 422, nil, "获取openID失败")
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	json := gojsonq.New().FromString(string(body)).Find("openid")
	openId := json.(string)

	response.Reponse(c, http.StatusOK, 200, gin.H{"openid": openId}, "获取成功")
}
